var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ua = require('mobile-agent');
var routes = require('./routes/index');
var api = require('./routes/api');
//var users = require('./routes/users');
var expressjwt = require('express-jwt');

var app = express();

//设置模板
app.engine('.html', require('ejs').renderFile);
app.set('view engine', 'html');
//全局配置

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//promise 减少异步回调
app.use(require('express-promise')());
//cookie
app.use(cookieParser());
//静态目录，可设置多个
app.use(express.static(path.join(__dirname, 'public')));
//区分移动端和PC端返回不同的viewLAYOUT。
app.use(function(req,res,next){
	var agent = ua(req.headers['user-agent']);
	if(agent.Mobile) {
		app.set('views', path.join(__dirname, 'views/mobile'));
	}else{
		app.set('views', path.join(__dirname, 'views/pc'));
	}
	next();
});
//视图公共数据
app.locals={
    title:'外卖订餐'
};

//路由注册和路由方法应该是不同的处理
app.use('/', routes);
app.use('/api', api);
//app.use('/users', users);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;
